<?php

namespace App\Http\Controllers;

use DB;
use App\Quotation;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Config;


class AnswerController extends Controller {

    public $data = array();

    public $goAuth = false;
    public $goReload = false;

    public function __construct(){
        session_start();
        $this->data['user_agent'] = $this->getUserAgent();

        if( empty($_SESSION['user_id']) ){
            $this->goAuth = true;
        }
    }


    function answerPage($id){
        if( $this->goAuth ){
            $state          = urlencode("http://".env("APP_URL")."/answer/$id");
            $redirectUrl    = Config::get("lib.oauth_uri")."/auth?client_id=".Config::get("lib.client_id")."&response_type=code&state=$state";
            return redirect($redirectUrl);
        }

        if( $id < 1 ){
            return Response::json(['error'=>true , 'message'=>'该回答不存在'] , 200);
        }

        $this->data['answer_id']        = $id;
        $this->data['user_id']          = $_SESSION['user_id'];
        $this->data['comment_count']    = 0;

        $url = Config::get('lib.comment_uri')."/comment/count?object=wenda&object_ids=$id&app_id=23&user_id=".$_SESSION['user_id'];

        $result = $this->curl_get( $url , $_SESSION['token'] , 'comment' );
        $result_arr = json_decode($result , true);
        if( isset($result_arr['error']) && !$result_arr['error'] && count($result_arr['result']) > 0 ){
            $this->data['comment_count'] = $result_arr['result'][0]['comment_count'];
        }

        $answer = DB::table('answer')
                        ->select('answer.*','user.name','user.icon')
                        ->join('user','user.id','=','answer.creator_id')
                        ->where('answer.id','=',$id)
                        ->where('answer.is_deleted','=',0)
                        ->get();
        if( count($answer) == 0 ){
            return Response::json(['error'=>true , 'message'=>'该回答不存在'] , 200);
        }
        $question_id = $answer[0]->question_id;

        $question = DB::table('question')->where('id','=',$question_id)->where('is_deleted','=',0)->get();
        if( count($question) == 0 ){
            return Response::json(['error'=>true , 'message'=>'该问题不存在'] , 200);
        }

        //查找该用户的顶踩举报状态
        $this->data['up'] = 0;
        $this->data['down'] = 0;
        $this->data['report'] = 0;
        $opera_results = DB::table('user_operation')
                            ->where('user_id' , '=' , $_SESSION['user_id'])
                            ->where('answer_id' , '=' , $id)
                            ->get();

        foreach( $opera_results as $key => $val ){
            switch ($val->type) {
                case '1':
                    $this->data['up'] = 1;
                    break;
                case '2':
                    $this->data['down'] = 1;
                    break;
                case '3':
                    $this->data['report'] = 1;
                    break;
                default:
                    break;
            }
        }

        $this->data['question'] = $question;
        $this->data['answer']   = $answer;

        $this->data['title']        = $question[0]->title;
        $this->data['description']  = $answer[0]->content;

        return view('answer' , $this->data);
    }


    //撰写答案页面
    function doAnswerPage($id){
        if( $this->goAuth ){
            $state          = urlencode("http://".env("APP_URL")."/do_answer/$id");
            $redirectUrl    = Config::get("lib.oauth_uri")."/auth?client_id=".Config::get("lib.client_id")."&response_type=code&state=$state";
            return redirect($redirectUrl);
        }

        if( $id < 1 ){
            return Response::json(['error'=>true , 'message'=>'该问题不存在'] , 200);
        }
        $question = DB::table('question')
                        ->select('id','title')
                        ->where('id','=',$id)
                        ->where('is_deleted','=',0)
                        ->get();
        if( count($question) == 0 ){
            return Response::json(['error'=>true , 'message'=>'该问题不存在'] , 200);
        }

        $this->data['question'] = $question;
        return view('do_answer' , $this->data);
    }


    //修改答案页面
    public function editAnswerPage($id){
        if( $this->goAuth ){
            $state          = urlencode("http://".env("APP_URL")."/edit_answer/$id");
            $redirectUrl    = Config::get("lib.oauth_uri")."/auth?client_id=".Config::get("lib.client_id")."&response_type=code&state=$state";
            return redirect($redirectUrl);
        }

        $answer = DB::table('answer')
                        ->select('answer.id' , 'answer.question_id' , 'question.title' , 'answer.content' )
                        ->join('question' , 'question.id' , '=' ,'answer.question_id')
                        ->where('answer.id','=',$id)
                        ->where('answer.creator_id','=',$_SESSION['user_id'])
                        ->get();
        if( count($answer) == 0 ){
            return Response::json(['error'=>true , 'message'=>'该回答不存在'] , 200);
        }
        $this->data['is_edit'] = 1;
        $this->data['answer'] = $answer;

        $question = DB::table('question')
                        ->select('id','title')
                        ->where('id','=',$answer[0]->question_id)
                        ->where('is_deleted','=',0)
                        ->get();
        if( count($question) == 0 ){
            return Response::json(['error'=>true , 'message'=>'该问题不存在'] , 200);
        }

        $this->data['question'] = $question;

        return view('do_answer' , $this->data);
    }


    //提交问题
    function doAnswer(){
        $user_id = $_SESSION['user_id'];
        if( !Input::has('content') ){
            return Response::json(['error'=>true , 'message'=>'回答的内容不能为空'] , 200);
        }
        if( !Input::has('question_id') || Input::get('question_id') < 1 ){
            return Response::json(['error'=>true , 'message'=>'回答的问题不能为空'] , 200);
        }
        $content = Input::get('content');
        $question_id = Input::get('question_id');

        $insert_arr = array(
            'question_id' => $question_id ,
            'creator_id' => $user_id ,
            'content' => $content ,
            'add_time' => date('Y-m-d H:i:s' , time())
            );
        $insert_id = DB::table('answer')->insertGetId($insert_arr);
        if( $insert_id > 0 ){
            return Response::json(['error'=>false , 'message'=>'回答内容提交成功'] , 200);
        }else{
            return Response::json(['error'=>true , 'message'=>'回答提交失败'] , 200);
        }
    }


    //举报答案
    function reportAnswer($id){
        if( !Input::has('value') || (Input::get('value')!=0 && Input::get('value')!=1) ){
            return Response::json(['error'=>true , 'message'=>'操作失败'] , 200);
        }
        $value = Input::get('value');

        $user_id = $_SESSION['user_id'];
        if( $id < 1 ){
            return Response::json(['error'=>true , 'message'=>'指定答案不存在'] , 200);
        }
        if( $value == 1 ){
            //取消举报
            DB::update("update answer set report = report-1 where id = $id");
            DB::delete("delete from user_operation where user_id = $user_id and answer_id = $id and type=3");
        }else{
            //举报
            DB::update("update answer set report = report+1 where id = $id");
            DB::table('user_operation')->insert( array('user_id'=>$user_id , 'answer_id'=>$id , 'type'=>3) );
        }

        return Response::json(['error'=>false , 'message'=>'举报成功'] , 200);
    }



    //顶答案
    function upAnswer($id){
        if( !Input::has('value') || (Input::get('value')!=0 && Input::get('value')!=1) ){
            return Response::json(['error'=>true , 'message'=>'操作失败'] , 200);
        }
        $value = Input::get('value');

        $user_id = $_SESSION['user_id'];
        if( $id < 1 ){
            return Response::json(['error'=>true , 'message'=>'指定答案不存在'] , 200);
        }
        if( $value == 1 ){
            //取消顶
            DB::update("update answer set up = up-1 where id = $id");
            DB::delete("delete from user_operation where user_id = $user_id and answer_id = $id and type=1");
        }else{
            //顶
            DB::update("update answer set up = up+1 where id = $id");
            DB::table('user_operation')->insert( array('user_id'=>$user_id , 'answer_id'=>$id , 'type'=>1) );
        }

        return Response::json(['error'=>false , 'message'=>'成功顶了一下'] , 200);
    }


    //踩答案
    function downAnswer($id){
        if( !Input::has('value') || (Input::get('value')!=0 && Input::get('value')!=1) ){
            return Response::json(['error'=>true , 'message'=>'操作失败'] , 200);
        }
        $value = Input::get('value');

        $user_id = $_SESSION['user_id'];
        if( $id < 1 ){
            return Response::json(['error'=>true , 'message'=>'指定答案不存在'] , 200);
        }
        if( $value == 1 ){
            //取消踩
            DB::update("update answer set down = down-1 where id = $id");
            DB::delete("delete from user_operation where user_id = $user_id and answer_id = $id and type=2");
        }else{
            //踩
            DB::update("update answer set down = down+1 where id = $id");
            DB::table('user_operation')->insert( array('user_id'=>$user_id , 'answer_id'=>$id , 'type'=>2) );
        }

        return Response::json(['error'=>false , 'message'=>'踩了一下'] , 200);
    }


    //作者修改答案
    function updateAnswer($id){
        if( $id < 1 ){
            return Response::json(['error'=>true , 'message'=>'该答案不存在'] , 200);
        }
        if( !Input::has('content') || Input::get('content') == '' ){
            return Response::json(['error'=>true , 'message'=>'修改内容不能为空'] , 200);
        }
        $content = Input::get('content');

        DB::table('answer')->where('id','=',$id)->update( array('content'=>$content) );

        return Response::json(['error'=>false , 'message'=>'修改成功'] , 200);
    }


    //作者删除答案
    function deleteAnswer($id){
        if( $id < 1 ){
            return Response::json(['error'=>true , 'message'=>'该答案不存在'] , 200);
        }
    }

}
